package com.wuzao.ObserverPattern.second;

import java.util.ArrayList;
import java.util.List;

/**
 * 天气数据站 主题接口的实现
 */
public class WeatherData implements Subject {

    //温度
    private float temperature;
    //湿度
    private float humidity;
    //压强
    private float pressure;

    List<Observer> observers;

    public WeatherData() {
        observers = new ArrayList<>();
    }


    public void setMeasurements(float temperature,float humidity,float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

    public float getTemperature() {
        return temperature;
    }

    public void setTemperature(float temperature) {
        this.temperature = temperature;
        measurementsChanged();
    }

    public float getHumidity() {
        return humidity;
    }

    public void setHumidity(float humidity) {
        this.humidity = humidity;
        measurementsChanged();
    }

    public float getPressure() {
        return pressure;
    }

    public void setPressure(float pressure) {
        this.pressure = pressure;
        measurementsChanged();
    }

    /**
     * 此方法嵌入WeatherData中的set方法中，
     * 只要数据发生改变，就会调用此方法
     */
    public void measurementsChanged(){
        notifyObservers();
    }

    @Override
    public String toString() {
        return "WeatherData{" +
                "temperature=" + temperature +
                ", humidity=" + humidity +
                ", pressure=" + pressure +
                '}';
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if(i>=0) observers.remove(i);

    }

    @Override
    public void notifyObservers() {
        for(Observer observer:observers){
            observer.update(this);
        }
    }
}
